<?php

namespace app\home\controller;

use app\home\model\Idfa724Model;
use app\home\model\Order;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use DateTime;
use DateTimeZone;
use think\Db;
use think\helper\hash\Md5;
use think\Model;
use think\Request;
use think\response\Json;

class Pay800022 extends BasePay
{

    // const  TEST_KEY = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAldC1fIrlU6AUmxpoDyOFyLLHPjc4xq+jq/xRxRHS5h99cuUSDmbVZYSJxx9rKJEIjRK61QK/ATM8u1x5Q8OI1XZGIoVfS8yZroIO4ObW+SvKdsihB+DMPTDPe6icvlnmmOucBXZLZQvSLR3s4jPp2uzEv4qJv9eEs4OnQhCjHNyjR7VH37EW34AI508jnULkE92uC49HweREpHjElkL7dvqTD5sxa1v6k2KjKW0sygMj4GKadeDAghKWpzyp9Q3h9Fw8NkebAJ/6v0fneVJHjrJ1++arOSwk+QwB2r5Z8KwqjijiVE1FlE1IJX9xShGrEtDL5TMIMNTPg8StQ58xIwIDAQAB';
    const  KEY = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiezIPm5dDShGAGqFPqoPZt9aoN4f6Xbd1Gpe3gYDIa9kN7sWXLiANC1vs96vNz3RNhmDlcKg3Jrh/tPNVKOHf2BBw3HGwsyHuSQ0BcYAuxTsQ2+GlVAyxCQSqV500mW2SsfrQdLr8IXmUasychY4Pngbs72A1mtDsZBsLSJFxlwLIO+MlWS2EGA4i3TUlPUTY9vBndVomgvUpwgHFk81/WJwFCBe7uVtfd9tPcFKgzAG5/sUBlYqejyBS467p2mzHRMsqLc/zT43kAczQgPTozk4GrQBNshyEt+HB+vHqt0H27cLNyeeQs2ccoTMMZDRP6MgCHLWy/DIbL2sLCCwwwIDAQAB';

    const alipayrsaPublicKey  = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnnfs5EzCakZGkEluF74zyMLc6peIy8smXkeArtiuVPbz+V+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a/GQbC/KiQ/nPlLKeXKp+tzvbddmns3r1tNMflsx1T5t01LO4F282HQ++LvetJPq+Cdam7oCzBs/8jEeivyaYl+IxmkguF59t637JQm431fXGcRyCQlAvozzqlkGGdXWD67j+oghCBtJZ3oV69I43+O0SJkJCHQKBgQCvgi3KsSt2ArGW/GL3uJHI1HtKudZRaXlKofD1l1NMNYCBTahjZSsSvqyA+hWENZ2225tPZ7kgrrHW2l6BYfg1xOgSr2ONQVCSEUjuxdGajjf3McejxLWEpIveDksSub+62MMag5My8to+oBF4htr+jch32Sbqj4iN74qmD7M70QKBgQDJcAmE9TIBhE8tZmtvTrhDRW49w17ut98100Xs+gWXKskrvEyJqQfB7ICUDpIZCwM2a5k+qvvZ/vIuD7DrhcrPOk6jzzTW1jMypJrRk5z33kpopuS1TJl1O5eXOxgXROdQvLfn0M6F+XNSZmmwL1F3CS7kdxJolxwiF2Ozf3ga2QKBgDP/tMN99Gt1ZtpeEpBkfcTrt0+veaELR+Vlz3dkC0jj/RvSP1abjcRy+7cG4UMXg4++xugiygW13HjUn/Vjal+75CpNDoi2VkHAn0QnFe/dvRUfCZAq4sDW4525zGJS6ExalouPehg5PZIaaLK1+cI7ja58hvwt5H5w/zouIqNRAoGBAKfcN8CI9x4uwHZSUNILyRwoAbdI6Ufcm+6dkvWh8GnyOGAfD3h0M6Szey+yFw7XgQzE/xmiE/MjM4jXkb926bQel8wDtipkKtKomQS/8pUuRNdt3sHcugjxl/UPNUpGJ3binCD6BH5DJAf2hMk2N6yAS2ZNBUN8CAaDVgWs1y2Z';
    
    public function __construct()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
    }

    public static function sign($content, $privateKeyPem)
    {
        $priKey = $privateKeyPem;
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($priKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        ($res) or die('私钥格式错误');
        openssl_sign($content, $sign, $res, OPENSSL_ALGO_SHA256);
        $sign = base64_encode($sign);
        return $sign;
    }

    public static function verify($content, $sign, $publicKeyPem)
    {
        $pubKey = $publicKeyPem;
        $res = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($pubKey, 64, "\n", true) .
            "\n-----END PUBLIC KEY-----";
        ($res) or die('公钥格式错误');

        //调用openssl内置方法验签，返回bool值
        $result = FALSE;
        $result = (openssl_verify($content, base64_decode($sign), $res, OPENSSL_ALGO_SHA256) === 1);
        return $result;
    }


    public function order()
    {
        parent::order();

        $dateTime = new DateTime();
        // 设置时区（如果需要）  
        $dateTime->setTimezone(new DateTimeZone('UTC'));
        // 格式化时间为所需的 RFC 3339 格式，包括纳秒  
        $formattedTime = $dateTime->format('Y-m-d\TH:i:s.') . substr($dateTime->format('u'), 0, 3) . '+00:00';

        $json_string = file_get_contents(env('PLATFORM.USD'));

        $config = json_decode($json_string, true);
        $usd  = $config[$this->order_array['goods_id']];
        if (empty($usd)) {
            mylog('计费点对应的美元金额找不到');
            throw new \Exception('计费点对应的美元金额找不到');
        }

        $currency = 'USD';
        $totalAmount = $usd['Mpay'];
        //根据配置修改对应的币种
        $server_config_info = Db::connect('db_config2')->table('server_config_info')->where(['ServerName'=>'conversion'])->find();
        if(!empty($server_config_info) && !empty($server_config_info['Content'])){
            $json_string = $server_config_info['Content'];
            $data = json_decode($json_string,true);
            if(in_array($this->order_array['channel_id'],$data['Channel'])){
                $user_ip_info = db('user_ip_info','db_operatelog')->where(['user_id'=>$this->order_array['userid']])->find();
                if(!empty($data[$user_ip_info['nation']])){
                    $currency = $data[$user_ip_info['nation']]['currency'];
                    $totalAmount = ceil($data[$user_ip_info['nation']]['rtion']*$usd['Mpay']);
                }
            }
        }

        $data = [
            'version' => '1.4',
            'keyVersion' => '1',
            'requestTime' => $formattedTime,
            'appId' => '73c20d34cc2e4375b81a57def9a1f382',
            'merchantNo' => 'P01010115853217',
            'data' => [
                'outTradeNo' => $this->order_array['id'],
                'integrate' => 'Hosted_Checkout',
                'subject' => empty($usd['Title'])?'goods':$usd['Title'],
                'totalAmount' => $totalAmount,
                'currency' => $currency,
                'userId' => $this->order_array['userid'],
                'reference' => $this->order_array['goods_id'],
                'frontCallbackUrl' => 'cafishing://main',
                'notifyUrl' => 'https://pay.carcadefishing.com/home/pay800022/notify',
            ]
        ];
        $data = json_encode($data);

        $sign = self::sign($data, self::rsaPrivateKey);
        $header = [
            "Accept: application/json",
            "Content-Type: application/json",
            "sign: $sign",
        ];
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => "https://pay-gate.payermax.com/aggregate-pay/api/gateway/orderAndPay",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_HTTPHEADER => $header,
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        mylog($response);
        mylog($err);
        curl_close($curl);

        exit($response);
    }

    public function test(){

            $curl = curl_init();
            curl_setopt_array($curl, [
            CURLOPT_URL => "www.payment.com/index.php/home/pay800022/notify",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode([
                'code' => 'APPLY_SUCCESS',
                'msg' => '',
                'keyVersion' => '1',
                'appId' => '3b242b56a8b64274bcc37dac281120e3',
                'merchantNo' => '020213827212251',
                'notifyTime' => '2022-01-17T09:33:54.540+00:00',
                'notifyType' => 'PAYMENT',
                'data' => [
                    'outTradeNo' => '20221018104872705555',
                    'tradeToken' => 'TOKEN20220117070423078754880',
                    'totalAmount' => 10000,
                    'currency' => 'IDR',
                    'country' => 'ID',
                    'status' => 'SUCCESS',
                    'completeTime' => '2023-10-20T03:28:23.092Z',
                    'paymentDetails' => [
                            [
                                'paymentMethodType' => 'WALLET',
                                'targetOrg' => 'DANA'
                            ]
                    ],
                    'reference' => '8342'
                ]
            ]),
            CURLOPT_HTTPHEADER => [
                "Accept: application/json",
                "Content-Type: application/json",
                "sign: FPFVT3o227JrFRbqu19boZCpVVTF9KznxyRawUmxpfXilHV/0yK46haPhAjNu1hPUMy7Vw/ILXhfzffNm4Fj0apWknlTY9OJxnSoQxS9BTFtc61tn5yV1q69x/kkBl82/qwg+XTJ4fOzy7Mar3VaC1E2PlDA6RkkKBUyNE6RYgsdB+Su7an4+4HVTNAnoe74WyvBgxTLMNg28igBTdqxaO3w/UBY6ObVp7vkqkQGdL1Y+HgmMYaAVwrM3+ALWGId0sJ+YqTY4WJ+0xCRGhaSnybiIjZsQEYyID68WNUfuavDLDsEhaMm/HfQvf5p0R1Ltovp3wwJnEbQcjY458iX5A=="
            ],
            ]);

            $response = curl_exec($curl);
            $err = curl_error($curl);

            curl_close($curl);

            if ($err) {
            echo "cURL Error #:" . $err;
            } else {
            echo $response;
            }
    }

    public function notify()
    {
        parent::notify();
        $params = $this->params;
        $header = Request::instance()->header();
        // $data = file_get_contents("php://input");
        mylog($params);
        mylog($header);
        try {
            //效验签名
            $sign = self::verify(json_encode($params,JSON_UNESCAPED_UNICODE),$header['sign'],self::KEY);
            if(!$sign){
                throw new \Exception('verify false' );
            }

            if ($params['code'] != 'APPLY_SUCCESS') {
                throw new \Exception('code false' );
            }

            if ($params['data']['status'] != 'SUCCESS') {
                throw new \Exception('status false');
            }
            //保存第三方单号
            $tradeLog = (new \app\home\model\TradeLog)->where(['id' => $params['data']['outTradeNo']])->find();
            if (empty($tradeLog)) {
                throw new \Exception('订单不存在');
            }
            $tradeLog->transactionID = $params['data']['tradeToken'];
            $tradeLog->save();

            if ($tradeLog['goods_id'] != $params['data']['reference'] ) {
                throw new \Exception('计费点不一致');
            }

            if ($tradeLog["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("800022 订单已经处理过了 订单id" . $tradeLog['id']);
                exit(json_encode(['msg'=>'Success','code'=>'SUCCESS']));
            }
            //发货
            $notifyService = new NotifyService();
            if ($notifyService->notifyProcess($tradeLog) == false) {
                throw new \Exception('notifyProcess false');
            }
            //facebook广告回传
            if(in_array($tradeLog->channel_id,(new AdFacebook())->channel_id)){
                $AdFacebook = new AdFacebook();
                $AdFacebook->pay($tradeLog->userid,$tradeLog->amount,$tradeLog->channel_id);
            }
            exit(json_encode(['msg'=>'Success','code'=>'SUCCESS']));

        } catch (\Exception $exception) {

            mylog('800022-error:' . $exception->getMessage() . ' line:' . $exception->getLine() . ' file:' . $exception->getFile());

            exit(json_encode(['msg'=>'Success','code'=>'SUCCESS']));
        }
    }
}
